//
//  NSString+Emoji.m
//  KeyboardForChat
//
//  Created by ruofei on 16/5/16.
//  Copyright © 2016年 ruofei. All rights reserved.
//

#import "NSString+Emoji.h"

@implementation NSString (Emoji)

- (BOOL)isEmoji{
    const unichar high = [self characterAtIndex:0];
    
    // Surrogate pair (U+1D000-1F77F)
    if (0xd800 <= high && high <= 0xdbff && self.length >= 2) {
        const unichar low = [self characterAtIndex:1];
        const int codepoint = ((high - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000;
        
        return (0x1d000 <= codepoint && codepoint <= 0x1f77f);
        
        // Not surrogate pair (U+2100-27BF)
    } else {
        return (0x2100 <= high && high <= 0x27bf);
    }
}

///编码EMOJI表情字符串
- (NSString *)encodeEmojiString {
    NSMutableString *attributeString = [[NSMutableString alloc] initWithString:self];
    NSString *regex_emoji = @"[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]";
    NSError *error = nil;
    NSRegularExpression *re = [NSRegularExpression
                               regularExpressionWithPattern:regex_emoji
                               options:NSRegularExpressionCaseInsensitive
                               error:&error];
    if (!re) {
        NSLog(@"[NSString toMessageString]: %@", [error localizedDescription]);
        return attributeString;
    }
    
    NSArray *resultArray = [re matchesInString:self options:0 range:NSMakeRange(0, self.length)];
    NSMutableArray *imageArray = [NSMutableArray arrayWithCapacity:resultArray.count];
    
    //根据匹配范围来用编码后的字符串进行相应的替换
    for(NSTextCheckingResult *match in resultArray) {
        //获取数组元素中得到range
        NSRange range = [match range];
        //获取原字符串中对应的值
        NSString *subStr = [self substringWithRange:range];
        //UTF8编码
        NSString *credentialName = [subStr emojiConvertObj];//[NSString emojiConvert:subStr];
        NSMutableDictionary *imageDic = [NSMutableDictionary dictionaryWithCapacity:2];
        [imageDic setObject:credentialName forKey:@"image"];
        [imageDic setObject:[NSValue valueWithRange:range] forKey:@"range"];
        //把字典存入数组中
        [imageArray addObject:imageDic];
    }
    //从后往前替换，否则会引起位置问题
    for (int i = (int)imageArray.count -1; i >= 0; i--) {
        NSRange range;
        [imageArray[i][@"range"] getValue:&range];
        //进行替换
        [attributeString replaceCharactersInRange:range withString:imageArray[i][@"image"]];
    }
    return attributeString;
}
///解码EMOJI表情字符串
- (NSString *)decodeEmojiString {
    NSMutableString *attributeString = [[NSMutableString alloc] initWithString:self];
    NSString *regex_emoji = @"\\[\\[(.*?)\\]\\]";
    
    NSError *error = nil;
    NSRegularExpression *re = [NSRegularExpression
                               regularExpressionWithPattern:regex_emoji
                               options:NSRegularExpressionCaseInsensitive
                               error:&error];
    if (!re) {
        NSLog(@"[NSString toMessageString]: %@", [error localizedDescription]);
        return attributeString;
    }
    
    NSArray *resultArray = [re matchesInString:self options:0 range:NSMakeRange(0, self.length)];
    NSMutableArray *imageArray = [NSMutableArray arrayWithCapacity:resultArray.count];
    
    //根据匹配范围来用解码后的字符串进行相应的替换
    for(NSTextCheckingResult *match in resultArray) {
        //获取数组元素中得到range
        NSRange range = [match range];
        //获取原字符串中对应的值
        NSString *subStr = [self substringWithRange:range];
        //UTF8解码
        NSString *credentialName = [subStr emojiRecoveryObj];//[NSString emojiRecovery:subStr];
        NSMutableDictionary *imageDic = [NSMutableDictionary dictionaryWithCapacity:2];
        [imageDic setObject:credentialName forKey:@"image"];
        [imageDic setObject:[NSValue valueWithRange:range] forKey:@"range"];
        //把字典存入数组中
        [imageArray addObject:imageDic];
    }
    //从后往前替换，否则会引起位置问题
    for (int i = (int)imageArray.count -1; i >= 0; i--) {
        NSRange range;
        [imageArray[i][@"range"] getValue:&range];
        //进行替换
        [attributeString replaceCharactersInRange:range withString:imageArray[i][@"image"]];
    }
    return attributeString;
}
///对emoji转码
- (NSString *)emojiConvertObj {
    NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet
                                          characterSetWithCharactersInString:charactersToEscape] invertedSet];
    NSString *encodeStr = [self stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    NSString *result = [NSString stringWithFormat:@"[[%@]]", encodeStr];
    return result;
}
///对emoji解码
- (NSString *)emojiRecoveryObj {
    NSString *trimBeginStr = [self stringByReplacingOccurrencesOfString:@"[[" withString:@""];
    NSString *trimEndStr = [trimBeginStr stringByReplacingOccurrencesOfString:@"]]" withString:@""];
    NSString *decodeStr = trimEndStr.stringByRemovingPercentEncoding;
    if (decodeStr == nil || [decodeStr isEqualToString:@""]) {
        return self;
    } else {
        return decodeStr;
    }
}


///将 表情进行转化 iOS[微笑] -> Android[face:12]
- (NSString *)emojiTransiOSAndroid:(BOOL)isiOS {
    NSString * text = self;
    //// 匹配表情
    NSArray<NSTextCheckingResult *> *emoticonResults = [[GDHFaceSourceManager regexEmoticon] matchesInString:self options:kNilOptions range:self.rangeOfAll];
    //NSUInteger emoClipLength = 0;
    for (NSTextCheckingResult *emo in emoticonResults) {
        if (emo.range.location == NSNotFound && emo.range.length <= 1) continue;
        NSRange range = emo.range;
        //range.location -= emoClipLength;
        NSString *emoString = [self substringWithRange:range];
        if (isiOS) {//iOS->Android
            NSString * emoValue = [GDHFaceSourceManager emoticoniOS_AndroidDic][emoString];
            if (emoValue.length > 0) {
                text = [text stringByReplacingOccurrencesOfString:emoString withString:emoValue];
            }
        }else{
            NSString * emoValue = [GDHFaceSourceManager emoticonAndroid_iOSDic][emoString];
            if (emoValue.length > 0) {
                text = [text stringByReplacingOccurrencesOfString:emoString withString:emoValue];
            }
        }
        //emoClipLength += range.length - 1;
    }
    return text;
}

@end



@implementation NSMutableAttributedString (MVVMWMoment)

/// 内容正则（链接， 表情 ， 手机号） fontSize： 表情的字体大小
- (void)mh_regexContentWithWithEmojiImageFontSize:(CGFloat)fontSize {
    /*/// 高亮背景
     YYTextBorder *border = [YYTextBorder new];
     border.cornerRadius = 0;
     border.insets = UIEdgeInsetsMake(0, -1, 0, -1);*/
    //border.fillColor = [UIColor color333333];
    
    /*/// 匹配链接
     NSArray<NSTextCheckingResult *> *linkUrlResults = [[MHMomentHelper regexLinkUrl] matchesInString:self.string options:kNilOptions range:self.yy_rangeOfAll];
     for (NSTextCheckingResult *link in linkUrlResults) {
     if (link.range.location == NSNotFound && link.range.length <= 1) continue;
     if ([self yy_attribute:YYTextHighlightAttributeName atIndex:link.range.location] == nil) {
     [self yy_setColor:MHMomentContentUrlTextColor range:link.range];
     /// 匹配userInfo
     /// 点击高亮
     YYTextHighlight *highlight = [YYTextHighlight new];
     // 将用户数据带出去
     highlight.userInfo = @{MHMomentLinkUrlKey:[self.string substringWithRange:link.range]};
     [highlight setBackgroundBorder:border];
     [self yy_setTextHighlight:highlight range:link.range];
     }
     }
     */
    
    /*/// 匹配电话号码
     NSArray<NSTextCheckingResult *> *phoneResults = [[MHMomentHelper regexPhoneNumber] matchesInString:self.string options:kNilOptions range:self.string.rangeOfAll];
     
     for (NSTextCheckingResult *phone in phoneResults) {
     if (phone.range.location == NSNotFound && phone.range.length <= 1) continue;
     if ([self yy_attribute:YYTextHighlightAttributeName atIndex:phone.range.location] == nil) {
     [self yy_setColor:MHMomentContentUrlTextColor range:phone.range];
     /// 匹配userInfo
     /// 点击高亮
     YYTextHighlight *highlight = [YYTextHighlight new];
     // 将用户数据带出去
     highlight.userInfo = @{MHMomentPhoneNumberKey:[self.string substringWithRange:phone.range]};
     [highlight setBackgroundBorder:border];
     [self yy_setTextHighlight:highlight range:phone.range];
     }
     }*/
    //// 匹配表情
    NSArray<NSTextCheckingResult *> *emoticonResults = [[GDHFaceSourceManager regexEmoticon] matchesInString:self.string options:kNilOptions range:self.yy_rangeOfAll];
    NSUInteger emoClipLength = 0;
    for (NSTextCheckingResult *emo in emoticonResults) {
        if (emo.range.location == NSNotFound && emo.range.length <= 1) continue;
        
        NSRange range = emo.range;
        range.location -= emoClipLength;
        if ([self yy_attribute:YYTextHighlightAttributeName atIndex:range.location]) continue;
        if ([self yy_attribute:YYTextAttachmentAttributeName atIndex:range.location]) continue;
        NSString *emoString = [self.string substringWithRange:range];
        NSString *imagePath = [GDHFaceSourceManager emoticonRealDic][emoString];
        if (imagePath.length <= 0) {
            imagePath = [GDHFaceSourceManager emoticonDic][emoString];
        }
        UIImage *image = [GDHFaceSourceManager imageWithPath:imagePath];
        if (!image) continue;
        NSAttributedString *emoText = [NSAttributedString yy_attachmentStringWithEmojiImage:image fontSize:fontSize];
        [self replaceCharactersInRange:range withAttributedString:emoText];
        emoClipLength += range.length - 1;
    }
}

@end
